# -*- coding: utf-8 -*-
#  自定义普通的tableModel
# @Time    ： 2022/2/14  10:39
# @Auther  ： 徐良
# File     :  tableModel.py

from PySide6.QtCore import Qt, QModelIndex, Signal
from PySide6.QtGui import QColor

from share.dataFactory import DataFactory
from share.baseFunction import getInstanceType
from baseClass.baseModel import BaseModel
from baseClass.baseRecord import BaseRecord
from baseClass.tools.tableToList import ListFromModel


class TableModel(BaseModel):
    """
    可编辑表格model
    """
    dataChangedSignal = Signal(BaseModel, QModelIndex)
    def __init__(self, args):

        super(TableModel, self).__init__()
        self.fieldNameList = []

        if 'baseDbType' in args:
            self.baseDbType = args['baseDbType']
        else:
            self.baseDbType = None

        if 'fieldNameList' in args:
            self.fieldNameList = args['fieldNameList']
        if 'sql' in args:
            self.sSql = args['sql']
        else:
            self.sSql = ''

        if 'model' in args and args['model'] is not None:
            self.model = args['model']
        else:
            if self.sSql != '':
                self.model = DataFactory.getQueryModelForSql(self.sSql, self.baseDbType)
            else:
                pass
                print('抛出错误')

        if 'alignList' in args:
            self.alignList = args['alignList']
        else:
            self.alignList = []

        if len(self.fieldList) == 0:
            listFromModel = ListFromModel(self.model)
            self.fieldList = listFromModel.getFieldList()

        self.dirty = False
        if len(self.fieldNameList) > 0:
            column = len(self.fieldNameList)
        else:
            column = self.model.columnCount()

        for i in range(0, column):
            self.fieldValList.append('')

        self.load(self.model)

    def rowCount(self, parent=QModelIndex()):
        """
        返回行数量。
        """
        return len(self.records)

    def columnCount(self, parent=QModelIndex()):
        """
        返回列数量。
        """
        return len(self.fieldList)

    def insertRows(self, position, rows=1, index=QModelIndex()):
        """
        插入行
        :param position: 插入起始行
        :param rows: 插入行数量
        :param index:
        :return:
        """
        self.beginInsertRows(QModelIndex(), position, position + rows - 1)
        for row in range(rows):
            self.records.insert(position + row, BaseRecord(self.fieldList, self.fieldValList))
        self.endInsertRows()
        self.dirty = True
        return True

    def headerData(self, section, orientation, role):
        """
        设置表头。
        """
        if role == Qt.TextAlignmentRole:
            if orientation == Qt.Horizontal:
                return int(Qt.AlignHCenter | Qt.AlignVCenter)

            return int(Qt.AlignHCenter | Qt.AlignVCenter)

        if role != Qt.DisplayRole:
            return None

        if role == Qt.DisplayRole and orientation == Qt.Horizontal:  # 返回行表头
            if len(self.fieldNameList) > 0:
                # if 0 <= section < len(self.fieldNameList):
                return self.fieldNameList[section]
            else:
                # if len(self.fieldList) > 0 and 0 < section <= len(self.fieldList):
                return self.fieldList[section]

        return int(section + 1)

    def data(self, index, role=Qt.DisplayRole):
        if (not index.isValid()) or not (0 <= index.row() <= len(self.records)):
            return None

        record = self.records[index.row()]
        column = index.column()

        if column >= len(self.alignList):  # 因为painter没有执行返回操作,执行横条拖拽时报错
            align = None
        else:
            align = self.alignList[column]

        if role == Qt.TextAlignmentRole:
            if align == 'left' or align == 'Qt.AlignLeft':
                return Qt.AlignLeft | Qt.AlignVCenter
            elif align == 'right' or align == 'Qt.AlignRight':
                return Qt.AlignRight | Qt.AlignVCenter
            elif align == 'center' or align == 'Qt.AlignCenter':
                return Qt.AlignCenter | Qt.AlignVCenter
            else:
                return Qt.AlignLeft | Qt.AlignVCenter
        elif role == Qt.ForegroundRole:
            # 设置字体颜色为红色
            if self.ROB == 1:
                return QColor(Qt.red)
            else:
                return QColor(Qt.black)


        if role == Qt.DisplayRole:
            field = self.fieldList[column]
            val = eval('record.' + field.lower())
            return val

        if role == Qt.EditRole:
            field = self.fieldList[column]
            val = eval('record.' + field.lower())
            return val

    def setData(self, index, value, role=Qt.EditRole):
        before = self.data(index)

        if index.isValid() and 0 <= index.row() <= len(self.records):
            self.beginResetModel()
            record = self.records[index.row()]
            column = index.column()
            if getInstanceType(value) == 'int':
                expression = 'record.' + self.fieldList[column].lower() + ' = int(value)'
            else:
                expression = 'record.' + self.fieldList[column].lower() + ' = str(value)'  # 界面的值赋给record对象
            exec(expression)

            self.endResetModel()

            if index.column() != 0 and before != value:
                self.dirty = True
                self.dataChangedSignal.emit(self, index)
            fl = len(self.fieldList)
            # 如果当前被编辑的字段名为fsel,并且column = 0 则不发出数据被编辑的信号
            if index.column() == 0 and (0 <= index.column() < fl):
                if self.fieldList[index.column()] == 'fsel':
                    return True
            return True


        return False

    def setROB(self, value):
        """
        设置红蓝字
        :param value:
        """
        if self.ROB != value:
            self.ROB = value
            # 发射信号，通知视图数据发生变化, 此处应该发红字变化信号，等待修正
            # self.dataChangedSignal.emit(self.index(0, 0), self.index(self.rowCount() - 1, self.columnCount() - 1))


    def getColForField(self, field_name):
        """
        获取字段名所处的列
        :return:
        """

        if field_name in self.fieldList:
            index = self.fieldList.index(field_name)
            return index
        else:
            return -1



